package com.cskaoyan.kpi.ip;

import com.cskaoyan.kpi.Summary;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

/**
 * @ClassName UniqueIpReducer
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/2/16 16:28
 * @Version V1.0
 **/
public class UniqueIpReducer extends Reducer<Text, Text, Summary, Text> {

    private String date = null;

    private int number = 0;

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        //相同的key会调用一次reduce，也就是相同的ip，调用一次reduce
        //保证只有一个唯一的reducer即可
        if(number == 0){
            Iterator<Text> iterator = values.iterator();
            if(iterator.hasNext()){
                date = iterator.next().toString();
            }
        }
        number ++;
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        Summary summary = new Summary(number, date, "uniqueIp", number + "", null);
        context.write(summary, new Text());
    }
}
